

package net.jjjshop.job.scheduled;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.entity.app.App;
import net.jjjshop.common.entity.order.Order;
import net.jjjshop.common.entity.order.OrderCreditPay;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.enums.OrderPayTypeEnum;
import net.jjjshop.common.enums.SettingEnum;
import net.jjjshop.common.factory.product.ProductFactory;
import net.jjjshop.common.service.app.AppService;
import net.jjjshop.common.service.order.OrderCreditPayService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.settings.vo.TradeVo;
import net.jjjshop.common.util.OrderUtils;
import net.jjjshop.common.util.SettingUtils;
import net.jjjshop.common.util.UserCouponUtils;
import net.jjjshop.common.util.UserUtils;
import net.jjjshop.common.util.alimini.AlipayUtils;
import net.jjjshop.job.service.order.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单定时任务、未付款关闭，自动确认收货，订单结算
 */

@Slf4j
@Component
public class ZmxyScheduled {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AppService appService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ProductFactory productFactory;
    @Autowired
    private OrderUtils orderUtils;
    @Autowired
    private UserCouponUtils userCouponUtils;
    @Autowired
    private UserUtils userUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderCreditPayService orderCreditPayService;

    /**
     * 每小时执行一次
     */
    @Scheduled(cron = "0 6 0/1 * * ? ")
    public void execute() throws Exception {
        // 扣款
      //  this.koukuan();

    }


    /**
     * 定时扣款
     */
    private void koukuan() throws AlipayApiException {
        // 查询截止时间未扣款的订单
        List<Order> items = orderService.list(new LambdaQueryWrapper<Order>().in(Order::getPayType, 40, 50)
                .eq(Order::getOrderStatus, 10)
                .eq(Order::getIsDelete, 0)
                .in(Order::getZmDeductStatus, 10, 30)
                .eq(Order::getAuthStatus, 20)
                .eq(Order::getAuthAuditStatus, 20)
                .le(Order::getPlanDeductionTime, new Date())//已经超过代扣时间
                .isNotNull(Order::getPayEndTime)
                .lt(Order::getPayEndTime, new Date()));
        // 订单id集
        List<Integer> orderIds = items.stream().map(Order::getOrderId).collect(Collectors.toList());
        // 循环扣款
        if (orderIds.size() > 0) {
            for (Order order:items) {
                //在扣款记录中加入日志
                BigDecimal shengyudaikou = order.getPayPrice().subtract(order.getDeductionMoney());
                order.setDeductionRecord(  "" + DateUtil.formatDateTime(new Date()) + "系统请求扣款,金额:"+shengyudaikou+"元;<br/>"+order.getDeductionRecord());
                OrderCreditPay orderCreditPay = orderCreditPayService.getOne(new LambdaQueryWrapper<OrderCreditPay>()
                        .eq(OrderCreditPay::getOrderId, order.getOrderId())
                        .eq(OrderCreditPay::getPayStatus, 10)
                        .orderByDesc(OrderCreditPay::getCreateTime)
                        .last("limit 1"));
                String remark=DateUtil.formatDateTime(new Date()) + "系统请求扣款,金额:" + shengyudaikou+"元;<br/>";

                if (orderCreditPay == null) {
                    orderCreditPay = new OrderCreditPay();
                    orderCreditPay.setOrderId(order.getOrderId());
                    orderCreditPay.setOutRequestNo(OrderUtils.geneOrderNo(order.getUserId()));
                    orderCreditPay.setPayStatus(10);
                    orderCreditPay.setPayPrice(shengyudaikou);
                    orderCreditPay.setPayType(order.getPayType());//免押扣款
                    orderCreditPay.setOutTradeNo(OrderUtils.geneOrderNo(order.getUserId()));
                    orderCreditPay.setRemark(orderCreditPay.getRemark() +remark);
                    orderCreditPayService.save(orderCreditPay);
                }else {
                    orderCreditPay.setRemark(remark+orderCreditPay.getRemark() );
                    orderCreditPayService.updateById(orderCreditPay);
                }
                if (order.getPayType().equals(OrderPayTypeEnum.ALIPAY_MY.getValue())) {
                    AlipayTradePayResponse response = AlipayUtils.tradePayMY(orderCreditPay.getOutTradeNo(), shengyudaikou, "扣款", order.getCreditBizOrderId());
                    orderCreditPay.setTradeNo(response.getTradeNo());
                    orderCreditPayService.updateById(orderCreditPay);
                }else {
                    User user = userService.getById(order.getUserId());
                    String s = AlipayUtils.tradeOrderPay(user.getOpenId(), shengyudaikou, order.getTradeNo(), orderCreditPay.getOutRequestNo());
                }
                orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getOrderId, order.getOrderId()).set(Order::getAuthRemark, order.getAuthRemark()+remark));


            }
        }
        // 记录日志
        if(orderIds.size() > 0){
            log.info(String.format("order scheduled close orderIds:%s", orderIds));
        }
    }

}
